package com.sillyhat.project.webapp.admin.controller;

import com.octo.captcha.service.CaptchaService;
import com.sillyhat.project.common.dto.Message;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project MGFaceFramework
 * @create 2017-03-23 15:05
 **/


@RequestMapping("captcha")
@Controller("captchaController")
public class CaptchaController {

    private static final Message MESSAGE_SUCCESS = Message.success("admin.message.success", new Object[0]);//操作错误
    private static final Message MESSAGE_ERROR = Message.error("admin.message.error", new Object[0]);//操作成功

    @Resource(name = "captchaService")
    private CaptchaService captchaService;

    private static final Logger log = LogManager.getLogger(CaptchaController.class);

    @RequestMapping(value = "/checkcode", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "验证码校验", response = Message.class, notes = "验证码校验")
    public Message checkCode(@ApiParam(required = true, name = "code", value = "验证码") @RequestParam(value = "code",defaultValue = "0") String code, HttpServletRequest request) {
        log.info("接收到的验证码为:{}",code);
        String captchaId = request.getSession().getId();
        try {
            boolean result = captchaService.validateResponseForID(captchaId, code.toUpperCase());
            if (result) {
                return MESSAGE_SUCCESS;
            }
        } catch (Exception e) {
            log.error("校验验证码发生异常:{}", e.getMessage());
        }
        return MESSAGE_ERROR;
    }

    @RequestMapping(value = "/getcode", method = RequestMethod.GET)
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        String captchId = request.getSession().getId();
        BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchId, request.getLocale());
        // 输出jpg的字节流
        ServletOutputStream responseOutputStream = null;
        try {
            responseOutputStream = response.getOutputStream();
            ImageIO.write(challenge, "jpg", responseOutputStream);
            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");
            responseOutputStream.flush();
        } catch (Exception e) {
            log.error("获取验证码出现错误:{}", e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            } catch (IOException e1) {
                log.error("发送错误码出现错误:{}", e1.getMessage());
            }
        } finally {
            IOUtils.closeQuietly(responseOutputStream);
        }
    }
}
